package org.jeecg.modules.ncmeapis.template.service.impl;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.ncmeapis.template.entity.SysPackTemplate;
import org.jeecg.modules.ncmeapis.template.entity.SysPackTemplatePrems;
import org.jeecg.modules.ncmeapis.template.mapper.SysPackTemplateMapper;
import org.jeecg.modules.ncmeapis.template.mapper.SysPackTemplatePremsMapper;
import org.jeecg.modules.ncmeapis.template.service.ISysPackTemplateService;
import org.jeecg.modules.ncmeapis.template.vo.SysPackTemplatePage;
import org.jeecg.modules.system.entity.SysPackPermission;
import org.jeecg.modules.system.entity.SysTenantPack;
import org.jeecg.modules.system.service.ISysPackPermissionService;
import org.jeecg.modules.system.service.ISysTenantPackService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 用户产品包模板
 * @Author: jeecg-boot
 * @Date:   2023-12-18
 * @Version: V1.0
 */
@Service
public class SysPackTemplateServiceImpl extends ServiceImpl<SysPackTemplateMapper, SysPackTemplate> implements ISysPackTemplateService {

	@Autowired
	private SysPackTemplateMapper sysPackTemplateMapper;
	@Autowired
	private SysPackTemplatePremsMapper sysPackTemplatePremsMapper;
	@Autowired
	private ISysTenantPackService sysTenantPackService;
	@Autowired
	private ISysPackPermissionService sysPackPermissionService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<SysPackTemplatePage> saveOrUpdateMain(Integer tenantId) {
		//清空主表
		sysPackTemplateMapper.clear();
		//清空附表
		sysPackTemplatePremsMapper.clear();
		//获取该项目下所有产品包并保存
		List<SysTenantPack> sysTenantPacks = sysTenantPackService.getSysTenantPackByTenantId(tenantId);
		List<SysPackTemplate> sysPackTemplates = sysTenantPacks.stream().map(entity -> {
			SysPackTemplate sysPackTemplate = new SysPackTemplate();
//			sysPackTemplate.setId(entity.getId());
			sysPackTemplate.setPackName(entity.getPackName());
			sysPackTemplate.setRemarks(entity.getRemarks());
			return sysPackTemplate;
		}).collect(Collectors.toList());
//		this.saveBatch(new ArrayList<>(sysPackTemplates));
		List<SysPackTemplatePage> sysPackTemplatePages = new ArrayList<>();
		//获取所有产品包的权限并保存
		for (SysPackTemplate sysPackTemplate:sysPackTemplates) {
			SysTenantPack sysTenantPack = this.queryByRoleNameAndProjectId(sysPackTemplate.getPackName(), tenantId);
			List<SysPackPermission> sysPackPermissions = sysPackPermissionService.getByPackId(sysTenantPack.getId());
			SysPackTemplatePage sysPackTemplatePage = new SysPackTemplatePage();
			BeanUtils.copyProperties(sysPackTemplate,sysPackTemplatePage);
			List<SysPackTemplatePrems> packTemplatePrems = sysPackPermissions.stream().map(entity -> {
				SysPackTemplatePrems sysPackTemplatePrems = new SysPackTemplatePrems();
				sysPackTemplatePrems.setPermissionId(entity.getPermissionId());
				return sysPackTemplatePrems;
			}).collect(Collectors.toList());
			sysPackTemplatePage.setSysPackTemplatePremsList(packTemplatePrems);
			this.saveMain(sysPackTemplate,packTemplatePrems);
			sysPackTemplatePages.add(sysPackTemplatePage);
		}
		return sysPackTemplatePages;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(SysPackTemplate sysPackTemplate, List<SysPackTemplatePrems> sysPackTemplatePremsList) {
		sysPackTemplateMapper.insert(sysPackTemplate);
		if(sysPackTemplatePremsList!=null && sysPackTemplatePremsList.size()>0) {
			for(SysPackTemplatePrems entity:sysPackTemplatePremsList) {
				//外键设置
				entity.setTemplateId(sysPackTemplate.getId());
				sysPackTemplatePremsMapper.insert(entity);
			}
		}
	}
	@Override
	public SysTenantPack queryByRoleNameAndProjectId(String roleName,Integer projectId) {
		//------------------------------------------------------------------------------------------------
		//获取登录用户信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		//是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】, admin给特权可以管理所有租户
//        if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && !"admin".equals(sysUser.getUsername())){
//            Integer loginSessionTenant = oConvertUtils.getInt(TenantContext.getTenant());
//            if(loginSessionTenant!=null && !loginSessionTenant.equals(Integer.valueOf(userId))){
//                result.error500("无权限访问他人租户！");
//                return result;
//            }
//        }
		//------------------------------------------------------------------------------------------------
		//通过登录用户筛选一遍packId
		List<SysTenantPack> sysTenantPacks1 = sysTenantPackService.getByUserId(userId);
		//通过tenantId筛选一遍packId
		List<SysTenantPack> sysTenantPacks2 = sysTenantPackService.getSysTenantPackByTenantId(projectId);
		Set<SysTenantPack> set = new HashSet<>();
		if (oConvertUtils.isEmpty(sysTenantPacks1) || oConvertUtils.isEmpty(sysTenantPacks2)) {
			return null;
		}
		set.addAll(sysTenantPacks1);
		set.addAll(sysTenantPacks2);
		List<SysTenantPack> sysTenantPacks = new ArrayList<>(set);
		if (sysTenantPacks.size() == 0) {
			return null;
		}
		for (SysTenantPack sysTenantPack : sysTenantPacks) {
			if (sysTenantPack.getPackName().equals(roleName)) {
				return sysTenantPack;
			}
		}
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(SysPackTemplate sysPackTemplate,List<SysPackTemplatePrems> sysPackTemplatePremsList) {
		sysPackTemplateMapper.updateById(sysPackTemplate);
		
		//1.先删除子表数据
		sysPackTemplatePremsMapper.deleteByMainId(sysPackTemplate.getId());
		
		//2.子表数据重新插入
		if(sysPackTemplatePremsList!=null && sysPackTemplatePremsList.size()>0) {
			for(SysPackTemplatePrems entity:sysPackTemplatePremsList) {
				//外键设置
				entity.setTemplateId(sysPackTemplate.getId());
				sysPackTemplatePremsMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		sysPackTemplatePremsMapper.deleteByMainId(id);
		sysPackTemplateMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			sysPackTemplatePremsMapper.deleteByMainId(id.toString());
			sysPackTemplateMapper.deleteById(id);
		}
	}
	
}
